package io.lvdaxian.mybatis16.mapping;

import io.lvdaxian.mybatis16.session.Configuration;
import io.lvdaxian.mybatis16.type.TypeHandler;
import io.lvdaxian.mybatis16.type.TypeHandlerRegistry;

import java.util.ArrayList;
import java.util.List;

/**
 * 结果 映射配置类
 *
 * @author lihh
 */
public class ResultMapping {
  // 配置信息
  private Configuration configuration;
  // 属性
  private String property;
  // 类
  private String column;
  // java 类型
  private Class<?> javaType;
  // 类型事件
  private TypeHandler<?> typeHandler;
  // flags 状态
  private List<ResultFlag> flags;
  
  ResultMapping() {
  }
  
  public static class Builder {
    
    private ResultMapping resultMapping = new ResultMapping();
    
    public Builder(Configuration configuration, String property, String column, Class<?> javaType) {
      resultMapping.configuration = configuration;
      resultMapping.property = property;
      resultMapping.column = column;
      resultMapping.javaType = javaType;
      resultMapping.flags = new ArrayList<>();
    }
    
    public Builder typeHandler(TypeHandler<?> typeHandler) {
      resultMapping.typeHandler = typeHandler;
      return this;
    }
    
    public Builder flags(List<ResultFlag> flags) {
      resultMapping.flags = flags;
      return this;
    }
    
    public ResultMapping build() {
      resolveTypeHandler();
      return resultMapping;
    }
    
    private void resolveTypeHandler() {
      if (resultMapping.typeHandler == null && resultMapping.javaType != null) {
        Configuration configuration = resultMapping.configuration;
        // 类型事件 注册器
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        // 从这里拿到事件类型
        resultMapping.typeHandler = typeHandlerRegistry.getTypeHandler(resultMapping.javaType, null);
      }
    }
    
  }
  
  public Configuration getConfiguration() {
    return configuration;
  }
  
  public String getProperty() {
    return property;
  }
  
  public String getColumn() {
    return column;
  }
  
  public Class<?> getJavaType() {
    return javaType;
  }
  
  public TypeHandler<?> getTypeHandler() {
    return typeHandler;
  }
  
  public List<ResultFlag> getFlags() {
    return flags;
  }
  
}
